import ViewBase from "./view/ViewBase"


/**
 * @description 框架工具
 * @author mirahs
 * @email 2892727493@qq.com
 */
export default class AppUtil {
    /**
     * 添加对齐组件(默认铺满父节点)
     * @param node 要添加对齐组件的节点
     * @param target 对齐目标(不设置默认父节点)
     */
    public static setWidget(node: cc.Node, target: cc.Node = null, top: number = 0, bottom: number = 0, left: number = 0, right: number = 0) {
        if (node.getComponent(cc.Widget)) return

        const widget = node.addComponent(cc.Widget)

        if (target) widget.target = target

        widget.isAlignTop = true
        widget.isAlignBottom = true
        widget.isAlignLeft = true
        widget.isAlignRight = true

        widget.top = top
        widget.bottom = bottom
        widget.left = left
        widget.right = right
    }

    // 异步封装
    public static async asyncWrap<T>(promise: Promise<T>): Promise<[T?, any?]> {
        try {
            return [await promise, null]
        } catch (error) {
            return [null, error]
        }
    }

    // 生成默认白色 100x100 大小 Sprite (单色) 节点
    public static newSpriteNode(name: string = 'newSpriteNode'): cc.Node {
        const buffer = Uint8Array.from([255, 255, 255, 255])

        const texture = new cc.Texture2D()
        texture.initWithData(buffer, cc.Texture2D.PixelFormat.RGBA8888, 1, 1)

        const spriteFrame = new cc.SpriteFrame()
        spriteFrame.setTexture(texture)

        const node = new cc.Node(name)
        const sprite = node.addComponent(cc.Sprite)
        sprite.sizeMode = cc.Sprite.SizeMode.CUSTOM
        sprite.spriteFrame = spriteFrame

        node.setContentSize(100, 100)

        return node
    }

    // localStorage setItem 封装(微信开发者工具和微信如果不把存储对象转为字符串再存储会存储失败)
    public static storeSet(key: string, value: any) {
        cc.sys.localStorage.setItem(key, JSON.stringify(value))
    }


    public static getClassName(viewCls: any): string {
        return (new viewCls() as ViewBase).getClassName()
    }
}
